package com.base.lib.ui;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import com.base.lib.mvp.present.BasePresenter;


/**
 * @author neo.duan
 * @date 2019-09-10 14:29
 * @desc BaseFragment懒加载，主要用于与ViewPager结合
 */
public abstract class BaseLazyFragment<P extends BasePresenter> extends BaseAppFragment<P> {

    /**
     * UI是否准备好:setUserVisibleHint是在onCreateView之前调用的
     */
    private boolean mIsPrepared;

    /**
     * 是否已经懒加载过
     */
    private boolean mHasLoad;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mIsPrepared = true;
        layLoad();
    }

    public void layLoad() {
        //用户可见|UI已准备|当前已显示
        if (getUserVisibleHint() && mIsPrepared && !mHasLoad) {
            onLayLoad();
            mHasLoad = true;
        }
    }

    @Override
    public void initData() {
        //do nothing
    }

    /**
     * 懒加载数据
     */
    public abstract void onLayLoad();

    /**
     * 在这里实现Fragment数据的缓加载.
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            onVisible();
        } else {
            onInVisible();
        }
    }

    public boolean isVisibleToUser() {
        return getUserVisibleHint();
    }

    public void onVisible() {
        layLoad();
    }

    public void onInVisible() {

    }
}
